package com.example.smart.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;

import com.example.lib.R;


//圆角ImageView
public class RoundImageView extends androidx.appcompat.widget.AppCompatImageView {

    private float width, height;
    private float[] rids;
    private final Path path = new Path();
    private final RectF rect = new RectF(0, 0, 0, 0);

    public RoundImageView(Context context) {
        this(context, null);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (Build.VERSION.SDK_INT < 18) {
            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        init(context, attrs);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        width = getWidth();
        height = getHeight();
        if (rect != null) {
            rect.right = width;
            rect.bottom = height;
        }
    }

    private void init(Context context, AttributeSet attrs) {
        //读取自定义属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView);
        int leftTopRadius = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_left_top_radius, 0);
        int rightTopRadius = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_right_top_radius, 0);
        int leftBottomRadius = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_left_bottom_radius, 0);
        int rightBottomRadius = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_right_bottom_radius, 0);

        typedArray.recycle();
        rids = new float[]{leftTopRadius, leftTopRadius, rightTopRadius, rightTopRadius, rightBottomRadius, rightBottomRadius, leftBottomRadius, leftBottomRadius};
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (width > 12 && height > 12 && rids != null && rect != null) {
            /*向路径中添加圆角矩形。radii数组定义圆角矩形的四个圆角的x,y半径。radii长度必须为8*/
            path.addRoundRect(rect, rids, Path.Direction.CW);
            canvas.clipPath(path);
        }
        super.onDraw(canvas);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }
}